#include "sIrrlichtTexture.h"
#include "sIrrlichtEngine.h"

namespace sgui
{
namespace engine
{

void sIrrlichtTexture::draw(const math::sRectf& rect) const
{
	if (m_tex)
    {
        m_engine.getDriver().draw2DImage(m_tex, m_engine.toRect<s32>(rect.to<s32>()), m_drawRect);
    }
}

void sIrrlichtTexture::drawClip(const math::sRectf& rect, const math::sRectf& clipRect) const
{
	if (m_tex)
    {
        m_engine.getDriver().draw2DImage(m_tex, m_engine.toRect<s32>(rect.to<s32>()), m_engine.toRect<s32>(clipRect.to<s32>()), 
            NULL, NULL, true);
    }
}
	
void sIrrlichtTexture::update(const preset::sPreset& preset)
{
	//
}

sIrrlichtTexture::sIrrlichtTexture(sIrrlichtEngine& engine, const res::sTextureResource& res, const preset::sTexturePreset& preset) :
	sTexture(engine, res, preset), m_tex(NULL), m_engine(engine)
{
	if (!res.getContents().empty())
	{
		const sgui::res::sResourceContent* cnt = res.getContents()[0];
		if (cnt)
		{
			const u32 file_size = cnt->getFileName().size();
			char* tmpdata = new char[file_size + 1];
			tmpdata[file_size] = 0;
			wcstombs(tmpdata, cnt->getFileName().c_str(), file_size);

			irr::io::IReadFile *file = engine.getDevice().getFileSystem()->
				createMemoryReadFile(cnt->getData(), cnt->getDataSize(), tmpdata);

			delete[] tmpdata;

			if (file)
			{
                engine.getDriver().setTextureCreationFlag(irr::video::ETCF_NO_ALPHA_CHANNEL, !preset.getAlphaChannel());

				m_tex = engine.getDriver().getTexture(file);
                const irr::core::dimension2d<s32>& sz = m_tex->getSize();

				m_drawRect = irr::core::rect<s32>(0, 0, sz.Width, sz.Height);

				file->drop();
			}
		}
	}
}

};
};